<?php
namespace Quality\Start\Infra;

use \Quality\Start\Infra\DependencyInjection\ContainerBuilder;
use \Symfony\Component\Routing\Loader\YamlFileLoader;
use \Symfony\Component\Config\FileLocator;
use \Symfony\Component\HttpKernel\Debug\ErrorHandler;
use \Symfony\Component\Routing\Router;

class ApplicationBuilder
{
    /**
     * @var string
     */
    const DEFAULT_BASE_CONTAINER = '\Quality\Start\Infra\DependencyInjection\ContainerBuilder';

    /**
     * @var string
     */
    protected static $containerBaseClass;

    /**
     * @var ContainerBuilder
     */
    protected $containerBuilder;

    /**
     * @var string
     */
    protected static $cacheDir;

    /**
     * @param string $basePath
     * @param string $containerConfig
     * @param string $cacheDir
     * @param string $containerConfig
     * @param string $routeConfig
     * @return \Quality\Start\Application
     */
    public static function build($basePath, $containerConfig, $routesPath, $cacheDir = null, $containerBaseClass = null)
    {
        static::$cacheDir = $cacheDir;
        static::$containerBaseClass = $containerBaseClass ?: static::DEFAULT_BASE_CONTAINER;
        $locator = new FileLocator(array($basePath));
        $loader = new YamlFileLoader($locator);
        $collection = $loader->load($routesPath);
        $builder = new static();
        $dependencyContainer = $builder->containerBuilder->getContainer(
            realpath($containerConfig),
            array($basePath),
            $collection
        );

        return new \Quality\Start\Application(
            new ErrorHandler(),
            $dependencyContainer
        );
    }

    /**
     * @param Router $router
     * @param ContainerBuilder $containerBuilder
     */
    public function __construct(
        ContainerBuilder $container = null
    ) {
        if ($container === null) {
            $container = new static::$containerBaseClass('\Quality\Start\Infra\DependencyInjection\Container',
                static::$cacheDir);
        }

        $this->containerBuilder = $container;
    }
}
